package com.kangjia.jasckson.hander;

import java.io.IOException;
import java.math.BigDecimal;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.kangjia.type.Decimal;


/**
 * 大数据转换json格式实现类
 * 
 * @author sshl
 * 
 */
public class DecimalJsonSerializer extends JsonSerializer<BigDecimal> {

	public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider)
			throws IOException, JsonProcessingException {
		if (value == null) {
			return;
		}
		jgen.writeString(Decimal.convert(value, Decimal.DECIMAL_DIGITS_HALF_UP, Decimal.DECIMAL_DIGITS_LENGTH)
				.toEngineeringString());
	}

	public static BigDecimal convert(BigDecimal value, String scale, int decimalDigits) {
		if (scale.equalsIgnoreCase(Decimal.DECIMAL_DIGITS_HALF_UP)) {
			return value.setScale(decimalDigits, BigDecimal.ROUND_HALF_UP);
		} else if (scale.equalsIgnoreCase(Decimal.DECIMAL_DIGITS_HALF_DOWN)) {
			return value.setScale(decimalDigits, BigDecimal.ROUND_HALF_DOWN);
		} else if (scale.equalsIgnoreCase(Decimal.DECIMAL_DIGITS_UP)) {
			return value.setScale(decimalDigits, BigDecimal.ROUND_UP);
		} else if (scale.equalsIgnoreCase(Decimal.DECIMAL_DIGITS_DOWN)) {
			return value.setScale(decimalDigits, BigDecimal.ROUND_DOWN);
		}
		return value.setScale(decimalDigits, BigDecimal.ROUND_HALF_UP);
	}
}
